<route lang="json5" type="page">
	{
	layout: 'default',
	style: {
	navigationStyle: 'custom',
	navigationBarTitleText: '个人',
	disableScroll: true, // 微信禁止页面滚动
	'app-plus': {
	bounce: 'none', // 禁用 iOS 弹性效果
	},
	},
	}
</route>

<template>
	<PageLayout :navbarShow="false">
		<view class="avatar-area">
			<wd-img width="100" height="100" :round="true" :radius="50" :src="getAvatarUrl"></wd-img>
		</view>
		<view class="info-area shadow-warp mb-5">
			<view class="user">
				<wd-text custom-class="title"
					:text="personalList.username ? personalList.username : personalList.nickName"></wd-text>
				<view class="tag">
					<view class="cuIcon-people mr-1"></view>
					<wd-text :text="personalList && personalList.permission === '0' ? '管理员' : '普通用户'"></wd-text>
				</view>
			</view>
			<view class="job">
				<wd-text custom-class="title" :text="getPositionName"></wd-text>
				<view class="tag">
					<view class="cuIcon-news mr-1"></view>
					<wd-text text="职务"></wd-text>
				</view>
			</view>
		</view>
		<scroll-view scroll-y>
			<wd-cell-group custom-class="shadow-warp" border clickable v-if="openId">
				<template v-for="(item, index) in dataSource" :key="index">
					<wd-cell :title="item.title" is-link @click="handleCell(item)">
						<template #icon>
							<view :class="item.class" class="mr-2"></view>
						</template>
					</wd-cell>
				</template>
				<!-- <button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
          登录
        </button> -->
			</wd-cell-group>
			<button v-else @click="login">登录</button>
		</scroll-view>
	</PageLayout>
</template>

<script lang="ts" setup>
	import { ref, reactive, computed, watch, onBeforeUnmount } from 'vue'
	import { cache, getFileAccessHttpUrl, hasRoute } from '@/common/uitls'
	import { onLaunch, onShow, onHide, onLoad, onReady } from '@dcloudio/uni-app'
	import { useToast, useMessage, useNotify } from 'wot-design-uni'
	import { useRouter } from '@/plugin/uni-mini-router'

	import { http } from '@/utils/http'
	import { useUserStore } from '@/store/user'
	import useUpload from '@/hooks/useUpload'
	import { getEnvBaseUrl } from '@/utils/index'
	import defAvatar from '@/static/default-avatar.png'
	import { tabStore } from '@/store/activity.ts';

	const tbStore = tabStore()

	// 状态管理
	const {
		setActivityTab
	} = tbStore


	const userStore = useUserStore()
	const toast = useToast()
	const router = useRouter()
	const message = useMessage()

	const personalList = reactive({
		avatar: '',
		realname: '',
		nickName: '',
		username: '',
		post: '',
		depart: '',
		permission: '',
		position: '',
		isMember: 1
	})

	const openId = computed(() => userStore.userInfo.openId)
	const nickName = computed(() => userStore.userInfo.nickName)
	const userInfo = ref({
		name: '',
		code: '',
	})
	let stopWatch = null
	const api = {
		positionUrl: '/sys/position/list',
		departUrl: '/sys/user/userDepartList',
		userUrl: '/sys/user/queryById',
		postUrl: '/sys/position/queryByCode',
		uploadUrl: `${getEnvBaseUrl()}/sys/common/upload`,
	}
	const dataSource = [
		{ key: 'organization', title: '组织', class: 'cuIcon-taoxiaopu text-cyan' },
		// { key: 'scan', title: '扫码', class: 'cuIcon-scan text-red' },
		// { key: 'location', title: '定位', class: 'cuIcon-location text-cyan' },
		{ key: 'setttings', title: '我的名片', class: 'cuIcon-settingsfill text-cyan' },
		{ key: 'shanghui', title: '加入商会', class: 'cuIcon-settingsfill text-cyan' },
		{ key: 'members', title: '会员管理', class: 'cuIcon-settingsfill text-cyan' },
		{ key: 'activity', title: '活动管理', class: 'cuIcon-settingsfill text-cyan' },
		{ key: 'exit', title: '退出登录', class: 'cuIcon-exit text-yellow' },
	]
	// 职位映射表
	const positionMap = {
		0: '会长',
		1: '副会长',
		2: '会员'
	};
	// 计算属性 - 获取职位名称（带默认值）
	const getPositionName = computed(() => {
		return positionMap[personalList.position] || '游客';
	});
	const getAvatarUrl = computed(() => {
		console.log("*********getAvatarUrl*************")
		console.log(userStore)
		if (personalList.avatar) {
			return personalList.avatar;
		}
		// const wechatAvatar = userStore.state.user.wechatInfo?.avatarUrl;
		// if (wechatAvatar) {
		// 	return wechatAvatar;
		// }
		return defAvatar;
	});
	const load = () => {
		http
			.get(api.userUrl, { id: userStore.userInfo.id })
			.then((res : any) => {
				console.log("*******获取用户信息2*******")
				console.log(res)
				if (res.success) {
					let perArr = res.result
					let avatar =
						perArr.avatar && perArr.avatar.length > 0
							? getFileAccessHttpUrl(perArr.avatar)
							: '/static/avatar_boy.png'
					personalList.avatar = avatar
					personalList.realname = perArr.realname
					personalList.username = perArr.username
					personalList.nickName = perArr.nickName
					personalList.depart = perArr.departIds
					personalList.permission = perArr.permission
					personalList.position = perArr.position
					personalList.isMember = perArr.isMember

					// getpost(perArr.post)
				}
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const getpost = (code) => {
		if (!code || code.length == 0) {
			personalList.post = '员工'
			return false
		}
		http
			.get(api.postUrl, { params: { code: code } })
			.then((res : any) => {
				console.log('postUrl', res)
				if (res.success) {
					personalList.post = res.result.name
				}
			})
			.catch((err) => {
				console.log(err)
			})
	}

	const ChooseImage = (params) => {
		const { loading, data, error, run } = useUpload({ name: 'file' }, { url: api.uploadUrl })
		if (stopWatch) stopWatch()
		run()
		stopWatch = watch(
			() => [loading.value, error.value, data.value],
			([loading, err, data], oldValue) => {
				if (loading == false) {
					if (err) {
						// toast.warning('修改失败')
						uni.hideLoading()
					} else {
						if (data) {
							editAvatar(data.message)
						}
					}
				}
			},
		)
	}
	const editAvatar = (avatar) => {
		http
			.put('/sys/user/appEdit', { id: userId.value, avatar })
			.then((res : any) => {
				if (res.success) {
					toast.success('修改成功~')
					userStore.editUserInfo({ avatar: getFileAccessHttpUrl(avatar) })
					personalList.avatar = getFileAccessHttpUrl(avatar)
				} else {
					toast.warning(res.message)
				}
				uni.hideLoading()
			})
			.catch((err) => {
				uni.hideLoading()
				toast.warning('修改失败')
			})
	}
	const scan = () => {
		// #ifndef H5
		uni.scanCode({
			success: function (res) {
				//条码内容包含QRCODELOGIN则是去扫码登录的逻辑
				if (res.result.indexOf('QRCODELOGIN') != -1) {
					const data = {
						qrcodeId: res.result,
						token: userStore.userInfo.token,
					}
					http({
						url: '/sys/scanLoginQrcode',
						data,
						header: { 'content-type': 'application/x-www-form-urlencoded' },
						method: 'POST',
					}).then((res : any) => {
						console.log('扫码接口返回内容res：', res)
						if (res.success) {
							toast.success(res.result)
						} else {
							toast.warning(res.result)
						}
					})
				}
			},
		})
		// #endif
		// #ifdef H5
		toast.warning('H5暂不支持')
		// #endif
	}
	const exit = () => {
		message
			.confirm({
				title: '提示',
				msg: '确定退出吗？',
			})
			.then(() => {
				userStore.clearUserInfo()
			})
	}

	const addShanghui = () => {
		if (userStore.userInfo.reviewStatus >= 0) {
		}
		http.post(`/chamber/ccUser/edit`, { "id": userStore.userInfo.id, "reviewStatus": 0 }).then((res) => {
			console.log(res)
			if (res.success) {
				uni.showToast({
					title: '添加成功',
					icon: 'none'
				})
			} else {
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}
		})
			.catch((err) => {
				console.error('获取用户信息错误:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}).finally(() => {

			})
	}

	const membersList = () => {
		uni.navigateTo({
			url: '/pages/memberManage/member',
		})
	}

	const activityList = () => {
		uni.navigateTo({
			url: "/pages/activitymanage/activity",
		})
	}

	const handleCell = (item) => {
		switch (item.key) {
			case 'scan':
				scan()
				break
			case 'location':
				router.push({ name: 'location' })
				break
			case 'organization':
				router.push({ name: 'organization' })
				break
			case 'setttings':
				router.push({ path: '/pages/mycard/card' })
				break
			case 'shanghui':
				// return addShanghui()
				router.push({ path: '/pages/user/joinSH' })
				break
			case 'members':
				return membersList()
				break
			case 'activity':
				return activityList()
				break
			case 'exit':
				exit()
				break
			default:
				toast.show('功能暂未开发~')
		}
	}
	const login = () => {
		console.log("*****login****")
		wx.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				userInfo.value.name = res.userInfo.nickName
			},
		})
		wx.login({
			success: (res) => {
				console.log(res)
				// text.value = res.code
				if (res.code) {
					http
						.post('/sys/login', { code: res.code, nickName: userInfo.value.name })
						.then((res : any) => {
							if (res.success) {
								const userInfo = res.result.userInfo
								userStore.setUserInfo({
									...userInfo,
									token: res.result.token,
									openId: userInfo.openId,
									nickName: userInfo.nickName,
									realname: userInfo.realname,
									avatar: userInfo.avatar,
									// tenantId: userInfo.loginTenantId,
									// localStorageTime: +new Date(),
								})
								personalList.nickName = userInfo.nickName
								openId.value = userInfo.openId
							}
						})
						.catch((err) => {
							console.log(err)
						})
				}
			},
		})
	}
	const onGetPhoneNumber = (e) => {
		console.log(e.detail.code) // 动态令牌
		console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
		console.log(e.detail.errno)
	}
	onBeforeUnmount(() => {
		stopWatch?.()
	})
	onShow(() => {
		console.log("**********onLoad*******")
		load()
	})
</script>

<style lang="scss" scoped>
	//
	.avatar-area {
		/* #ifdef MP-WEIXIN */
		background-image: url('https://static.jeecg.com/upload/test/blue_1595818030310.png');
		/* #endif */
		/* #ifndef MP-WEIXIN */
		background-image: url('@/static/blue.png');
		/* #endif */
		background-size: cover;
		height: 400upx;
		display: flex;
		justify-content: center;
		padding-top: 40upx;
		overflow: hidden;
		position: relative;
		flex-direction: column;
		align-items: center;
		color: #fff;
		font-weight: 300;
		text-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
	}

	.info-area {
		display: flex;
		padding: 30upx;
		background-color: #fff;
		color: #8799a3;

		:deep(.wd-text.is-default) {
			color: var(--color-grey);
		}

		.user,
		.job {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;

			.tag {
				display: flex;
				align-items: center;
			}

			:deep(.wd-text.title) {
				font-size: 18px;
				min-height: 18px;
				margin-bottom: 16upx;
			}
		}

		.user {
			border-right: 0.5px solid rgba(0, 0, 0, 0.1);

			:deep(.wd-text.title) {
				color: #f37b1d;
			}
		}

		.job {
			:deep(.wd-text.title) {
				color: #39b54a;
			}
		}
	}

	:deep(.wd-cell-group) {
		margin: 0 26upx;
		border-radius: 18upx;
		overflow: hidden;
		--wot-cell-line-height: 32px;

		.wd-cell {
			--wot-cell-title-fs: 15px;
			--wot-cell-title-color: var(--color-grey);

			.wd-cell__left {
				font-size: 15px;
			}
		}
	}
</style>